import React, {createContext, useContext, useState, useEffect} from 'react';

interface ThemeContextType {
    theme: 'light' | 'dark';
    toggleTheme: () => void;
}

const ThemeContext = createContext<ThemeContextType>({
    theme: 'light',
    toggleTheme: () => {
    }
});

export const useTheme = () => useContext(ThemeContext);
/*
创建context对象，

<Context.Provider>
所有需要共享这个上下文的组件必须被包裹在这个 Provider 内部。
可以动态改变传入的值。
<ThemeContext.Provider value={{ theme, toggleTheme }}>
  {children}
</ThemeContext.Provider>;


 */

export const ThemeProvider: React.FC<{ children: React.ReactNode }> = ({children}) => {
    const [theme, setTheme] = useState<'light' | 'dark'>(() => {
        // 从 localStorage 获取保存的主题，如果没有则使用亮色主题
        const savedTheme = localStorage.getItem('theme');
        return (savedTheme as 'light' | 'dark') || 'light';
    });

    useEffect(() => {
        // 保存主题到 localStorage
        localStorage.setItem('theme', theme);
        // 更新 body 的 data-theme 属性
        document.body.setAttribute('data-theme', theme);
    }, [theme]);

    const toggleTheme = () => {
        setTheme(prevTheme => prevTheme === 'light' ? 'dark' : 'light');
    };

    return (
        <ThemeContext.Provider value={{theme, toggleTheme}}>
            {children}
        </ThemeContext.Provider>
    );
}; 